--
-- some general-purpose utility functions... placed here for testing purposes
--

-- Autovivify a structure.
-- http://en.wikipedia.org/wiki/Autovivification
function autovivify(s, ...)
   if not s then s = {} end
   for _,v in ipairs{...} do
      if not s[v] then s[v] = {} end
      s = s[v]
   end
   return s
end

-- Split text into a list consisting of the strings in text,
-- separated by strings matching delimiter (which may be a pattern). 
-- example: strsplit(",%s*", "Anna, Bob, Charlie,Dolores")
-- stolen from http://lua-users.org/wiki/SplitJoin
function strsplit(delimiter, text)
  local list = {}
  local pos = 1
  if string.find("", delimiter, 1) then -- this would result in endless loops
    error("delimiter matches empty string!")
  end
  while 1 do
    local first, last = string.find(text, delimiter, pos)
    if first then -- found?
      table.insert(list, string.sub(text, pos, first-1))
      pos = last+1
    else
      table.insert(list, string.sub(text, pos))
      break
    end
  end
  return list
end

-- ------------------------------------------------------------------------
-- CSV functions
-- stolen from http://lua-users.org/wiki/CsvUtils
-- Used to escape "'s by toCSV
function escapeCSV (s)
   if string.find(s, '[,"]') then
      s = '"' .. string.gsub(s, '"', '""') .. '"'
   end
   return s
end

-- Convert from CSV string to table
function fromCSV (s)
   s = s .. ','        -- ending comma
   local t = {}        -- table to collect fields
   local fieldstart = 1
   repeat
      -- next field is quoted? (start with `"'?)
      if string.find(s, '^"', fieldstart) then
	 local a, c
	 local i  = fieldstart
	 repeat
            -- find closing quote
            a, i, c = string.find(s, '"("?)', i+1)
	 until c ~= '"'    -- quote not followed by quote?
	 if not i then error('unmatched "') end
	 local f = string.sub(s, fieldstart+1, i-1)
	 table.insert(t, (string.gsub(f, '""', '"')))
	 fieldstart = string.find(s, ',', i) + 1
      else                -- unquoted; find next comma
	 local nexti = string.find(s, ',', fieldstart)
	 table.insert(t, string.sub(s, fieldstart, nexti-1))
	 fieldstart = nexti + 1
      end
   until fieldstart > string.len(s)
   return t
end

-- Convert from table to CSV string
function toCSV (tt)
   local s = ""
   for _,p in pairs(tt) do
      s = s .. "," .. escapeCSV(p)
   end
   return string.sub(s, 2)      -- remove first comma
end

-- ------------------------------------------------------------------------
-- break up asteroid string into a table
--
function roidsplit(s)
   local r = {}
   r.temp = string.match(s, "Temperature: ([%d%.]+) K")
   local k
   local v
   for k, v in string.gmatch(s, "(%w+) Ore: ([%d%.]+)%%") do
      r[k] = v
   end
   return r
end

